<?php

namespace app\api\controller;

use app\BaseController;
use app\Request;
use broadcast\services\UtilService as Util;
use app\models\user\Users;
use app\models\user\UserToken;
use app\common\service\TenImService;
use app\models\system\SystemWebsite;
use broadcast\redis\setRedis;
use broadcast\services\WechatServices;


class WechatController extends BaseController
{
    //网页授权
    public function authorization(Request $request)
    {
        $datas = Util::postMore([
            ['roomid','']
        ]);
        session('website', $request->website());
        $website = setRedis::getCache(session("website"),'info');
        if (empty($website)) {
            $website = SystemWebsite::where("website_ident",session("website"))->find();
            if ($website) $website = $website->toArray();
            setRedis::setCache(session("website"),"info",$website,0);
        }
        $wechat = new WechatServices(['type'=>'pc']);
        $data = $wechat->auth("https://measureback.wm63.com/api/wechat/login/".$website['id'].'/'.$datas['roomid']."/pc");
        $url = $data->getTargetUrl();
        
        return app("json")->success(['link' => $url]);
    }

    //移动端授权
    public function moblieAuth (Request $request)
    {
        $datas = Util::postMore([
            ['roomid','']
        ]);

        session('website', $request->website());
        $website = setRedis::getCache(session("website"),'info');
        if (empty($website)) {
            $website = SystemWebsite::where("website_ident",session("website"))->find();
            if ($website) $website = $website->toArray();
            setRedis::setCache(session("website"),"info",$website,0);
        }
        $wechat = new WechatServices(['type'=>'moblie']);
        $data = $wechat->auth("https://measureback.wm63.com/api/wechat/login/".$website['id'].'/'.$datas['roomid']."/m");
        $url = $data->getTargetUrl();
        return app("json")->success(['link' => $url]);
    }

    //处理用户信息 
    public function login ($ident,$roomid,$code,$type)
    {
        $website = SystemWebsite::where("id",$ident)->field("website_ident,reception_domain")->find();
        if ($website) $website->toArray();
        session("website",$website['website_ident']);
        $website['reception_domain'] = "https://measure.wm63.com/index";
        $url = $website['reception_domain']."/".reversibleEncryption($website['website_ident'])."/".$roomid;
        $ip = getIps();
        if ($type =='m') {
            $type = "moblie";
        }
        
        $wechat = new WechatServices(['type'=>$type]);
        $user = $wechat->userinfo();
        
        $use = $user->getOriginal();

        $info = Users::where("openid",$use['openid'])->find();
        if (!empty($info)) {
            $info = $info->toArray();
            if ($info['group'] == 0) {
                $info = false;
            }
            //用户登录记录    start
            //用户登录记录    end

            // 更新用户信息
            if ($ip != '') {
                Users::where("id", $info['id'])->update(['lately_time' => time(), 'create_ip' => setIp($ip), 'create_home' => ascriptions($ip), 'online' => 1]);
                $info['create_ip'] = setIp($ip);
                $info['create_home'] = ascriptions($ip);
            }

            $info['lately_time'] = time();
            
            $info['online'] = 1;
            
            $url .= "/".$info['id'];
            Header("Location: $url");die;
        }else{
            $use['password'] = md5(123456);
            $useList = [
                'rooms' => $roomid,
                'create_time' => time(),
                'lately_time' => time(),
                'password' => $use['password'],
                'username' => $type.time().rand(0,10),
                'nickname' => $use['nickname'],
                'online'   => 1,
                "openid" => $use['openid'],
                'group' => 3
            ];

            if ($ip != '') {
                $useList['create_ip'] = setIp($ip);
                $useList['create_home'] = ascriptions($ip);
            }

            $model = new Users();
            $save = $model->save($useList);


            if ($save) {
                $users =  Users::where("id",$model->id)->find()->toArray();
                $url .= "/".$model->id;
            
                Header("Location: $url");die;
            }else{
                Header("Location: $url");die;
            }
        }
        
        
    }


    public function signs (Request $request) 
    {
        $data = Util::postMore([
            ['roomid',''],
            ['uid',''],
        ]);

        session('website', $request->website());
        $info = setRedis::getUserCache(session("website"), 'usersList#' . $data['uid'] . ':*');
    
        if (!$info) {
            $info = Users::where('id', $data['uid'])->find();
            if (empty($info)) return app("json")->fail("用户不存在");
            setRedis::setCache(session("website"), "usersList#" . $info['id'] . ":" . $info['username'], $info->toArray(), 0);
        } else {
            $info = $info['data'];
        }
        if ($info['group'] == 0) {
            $info = false;
        }
        if ($info) {
            $time = strtotime("+ 500hour");
            $token = UserToken::tokenCreate($info['id'], $time);
            // 获取IM配置
            $imSettings = TenImService::getSettings($data['roomid'], $info);

            //处理多余数据
            unset($info['id']);
            unset($info['password']);
            unset($info['create_time']);
            unset($info['create_ip']);
            unset($info['lately_time']);
            unset($info['create_home']);
            unset($info['openid']);
            unset($info['realname']);
            unset($info['website']);
            unset($info['status']);
            unset($info['update_time']);
            unset($info['extension']);
            unset($info['online']);
            unset($info['nickname']);

            $info['balance'] = round($info['balance'], 2);

            return app("json")->success('登录成功', ['token' => $token, 'expires_time' => $time, 'userInfo' => $info, 'imSettings' => $imSettings]);
        }

        return app("json")->fail("用户名或密码不正确");
    }


}